package com.ruoyi.project.system.file.controller;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.UUIDUtil;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.file.domain.File;
import com.ruoyi.project.system.file.service.IFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 附件Controller
 * 
 * @author ruoyi
 * @date 2022-07-21
 */
@Slf4j
@Controller
@RequestMapping("/system/file")
public class FileController extends BaseController
{
    private String prefix = "system/file";

    @Autowired
    private IFileService fileService;
    @Autowired
    private ServerConfig serverConfig;

    @RequiresPermissions("system:file:view")
    @GetMapping()
    public String file()
    {
        return prefix + "/file";
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("system:file:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(File file)
    {
        startPage();
        List<File> list = fileService.selectFileList(file);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("system:file:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(File file)
    {
        List<File> list = fileService.selectFileList(file);
        ExcelUtil<File> util = new ExcelUtil<File>(File.class);
        return util.exportExcel(list, "【请填写功能名称】数据");
    }

    /**
     * 新增【请填写功能名称】
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存【请填写功能名称】
     */
    @RequiresPermissions("system:file:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(File file)
    {
        return toAjax(fileService.insertFile(file));
    }

    /**
     * 修改【请填写功能名称】
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        File file = fileService.selectFileById(id);
        mmap.put("file", file);
        return prefix + "/edit";
    }

    /**
     * 修改保存【请填写功能名称】
     */
    @RequiresPermissions("system:file:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(File file)
    {
        return toAjax(fileService.updateFile(file));
    }

    /**
     * 删除【请填写功能名称】
     */
    @RequiresPermissions("system:file:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(fileService.deleteFileByIds(ids));
    }

    /**
     * 上传附件
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file, HttpServletRequest request) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            File fileInfo = FileUploadUtils.uploadFile(filePath, file);
            String url = serverConfig.getUrl() + fileInfo.getStaticPath();
            fileInfo.setUrl(url);
            fileInfo.setId(UUIDUtil.getUUID());
            String pid = request.getParameter("pid");
            if (StringUtils.emptyStr(pid)) {
                pid = UUIDUtil.getUUID();
            }
            fileInfo.setPid(pid);
            // 根据PID删除附件
            String del = request.getParameter("del");
            if (!StringUtils.emptyStr(del) && "1".equals(del)) {
                if (!StringUtils.emptyStr(pid)) {
                    fileService.deleteFileByPid(pid);
                }
            }
            fileService.insertFile(fileInfo);
            return AjaxResult.success("文件上传成功", fileInfo);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 下载
     * @param id
     * @param response
     * @param request
     */
    @GetMapping("/download/{id}")
    @ResponseBody
    public void fileDownload(@PathVariable("id") String id, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (StringUtils.isEmpty(id)) {
                throw new Exception("参数异常");
            }
            File fileInfo = fileService.selectFileById(id);
            if (fileInfo == null) {
                throw new Exception("文件不存在");
            }
            String realFileName = fileInfo.getName();
            String filePath = fileInfo.getPath();

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 删除文件
     * @param id
     * @return
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public AjaxResult deletFile(@PathVariable("id") String id, HttpServletRequest request) {
        try {
            if (StringUtils.isEmpty(id)) {
                throw new Exception("参数异常");
            }
            File fileInfo = fileService.selectFileById(id);
            if (fileInfo == null) {
                throw new Exception("文件不存在");
            }
            FileUtils.deleteFile(fileInfo.getPath());
            fileService.deleteFileById(id);
            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            log.error("文件删除失败", e);
        }
        return AjaxResult.error("文件删除失败");
    }
}
